package com.lb.uts.service.policy;


import com.lb.uts.constants.LogConstants;
import com.lb.uts.entity.ScheduleJob;
import com.lb.uts.util.PolicyUtil;
import com.lb.uts.entity.CacheClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Random;

import static com.lb.uts.util.PolicyUtil.JOB_IP_LIST_CHANGING;

/**
 * 随机策略，使用随机数返回一个执行器信息
 *
 * @author liangb
 * @version 3.0
 * @date 2019/4/28 11:58
 */
@Service
public class RandomSchedulingPolicy implements ISchedulingPolicy<CacheClient> {

    private static final Logger logger = LoggerFactory.getLogger(RandomSchedulingPolicy.class);

    @Override
    public CacheClient getSuitActiveClient(ScheduleJob job) {
        String systemName = job.getSystemName();
        while (true) {
            if (!JOB_IP_LIST_CHANGING) {
                List<CacheClient> jobIps = PolicyUtil.JOB_IP_LIST.get(systemName);
                if (CollectionUtils.isEmpty(jobIps)) {
                    logger.info(LogConstants.RANDOM_SCHEDULING_POLICY + "没有合适的执行器");
                    return null;
                }
                //随机取出一个ip
                int count = jobIps.size();
                Random random = new Random();
                int next = random.nextInt(count);
                return jobIps.get(next);
            } else {
                //此时后台线程正在刷新内存，等待，继续尝试
                logger.info(LogConstants.RANDOM_SCHEDULING_POLICY + "后台线程正在更新ip list，等待");
            }
        }
    }
}
